import { Component, OnInit, ElementRef, Renderer2, OnDestroy, AfterViewChecked } from '@angular/core';
import { NavController, NavParams, ModalController } from '@ionic/angular';
import { DataService } from '@services/data.service';
// import { LiftPage } from '../../device/lift/lift';
import { LiftTypeService } from '@services/liftType.service';
import { Router, ActivatedRoute } from '@angular/router';
import { EmitService } from '@services/emit.service';
import { CacheService } from '@services/cache.service';
import { Observable } from 'rxjs';
import { DeviceVideoModal } from '@modals/device-video/device-video';

@Component({
  selector: 'room-lift',
  templateUrl: 'page.html',
  styleUrls: ['lift.scss'],
})

export class RoomLiftPage implements OnInit, AfterViewChecked {
  sysName;                     // 获取页面显示名称
  projectId;                   // 项目ID
  alarmInfos;                  // 告警信息
  deviceSysId;                 // 设备ID
  runs = 0;                    // 正常
  stops = 0;                   // 停梯
  faults = 0;                  // 告警
  services = 0;                // 维保
  roomModes = [];              // 获取房间及设备参数
  _refreshInterval;            // 页面刷新定时器
  autoScrollInterval = null;   // 告警消息定时器
  Params;
  areaId;                      // 房间ID
  iconShow = true;
  videoList;                   // 电梯下所有的摄像头
  deviceVideoList;             // 电梯房间摄像头列表
  areaIds = [];                     // 所有房间
  constructor(
    public el: ElementRef,
    public renderer: Renderer2,
    // public navParams: NavParams,
    public dataservice: DataService,
    public liftService: LiftTypeService,
    private activatedRoute: ActivatedRoute,
    private navCtrl: NavController,
    private emitService: EmitService,
    private cache: CacheService,
    private modalCtrl: ModalController
  ) {
    this.activatedRoute.queryParams.subscribe(params => {
      this.projectId = params.projectId;
      this.deviceSysId = params.systemId;
      this.sysName = params.systemName;
      this.iconShow = params.iconShow === 'false' ? false : true
    });
  }

  ngOnInit() {
  }

  ngAfterViewChecked() {
    this.toResult();
    this.WordResult();
  }

  ionViewWillEnter() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements != null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'none';
      });
    }
    this.getLiftParams(this.projectId, this.deviceSysId).subscribe(data => {
      this.roomModes = data;
      console.log('最终电梯数据', data)
    });
    this._refreshInterval = setInterval(() => {
      this.getLiftParams(this.projectId, this.deviceSysId).subscribe(data => {
        this.roomModes = data;
        console.log('最终电梯数据', data)
      });
    }, 10000)
  }

  ionViewWillLeave() {
    console.log('离开')
    if (this._refreshInterval) {
      clearInterval(this._refreshInterval);
    }
  }

  /**
  * 获取房间及设备类型参数
  * @param projectId
  * @param deviceSysId
  */
  getLiftParams(projectId, deviceSysId): Observable<any> {
    return new Observable(responseObserver => {
      this.dataservice.getLifts(projectId, deviceSysId).subscribe(res => {
        console.log('电梯设备', res.data.datas)
        for (const data of res.data.datas) {
          this.areaIds.push(data.areaId);
        }
        this.areaIds = this.unique(this.areaIds);
        let roomLifts;
        if (res.data && res.data.datas) {
          this.getVideoList(this.areaIds);
          this.refreshData(res.data.datas, projectId, deviceSysId).subscribe(data => {
            roomLifts = data;
            responseObserver.next(roomLifts);
            responseObserver.complete();
          });
          // this._refreshInterval = setInterval(() => {
          // this.getVideoList(this.areaIds);
          // this.refreshData(res.data.datas, projectId, deviceSysId).subscribe(data => {
          //   roomLifts = data;
          //   responseObserver.next(roomLifts);
          //   responseObserver.complete();
          // });
          // }, 10000);
        }
      });
    });
  }

  unique(arr) {
    return Array.from(new Set(arr))
  }

  refreshData(data, projectId, deviceSysId): Observable<any> {
    return new Observable(responseObserver => {
      let roomLift;
      roomLift = data;
      this.getLiftDeviceParams(roomLift).subscribe(res => {
        console.log(res)
        this.addAlarmToDevice(res, projectId, deviceSysId).subscribe(data => {
          console.log(data)
          roomLift = this.dealData(data);
          responseObserver.next(roomLift);
          responseObserver.complete();
        });
      });
    });
  };

  // 按照设备类型分组
  getGroup(data) {
    console.log(data);
    const map = {};
    const dest = [];
    for (let i = 0; i < data.length; i++) {
      const ai = data[i];
      if (ai.dataType === 1) {
        if (!map[ai.deviceTypeId]) {
          dest.push({
            areaName: ai.areaName,
            deviceId: ai.deviceId,
            deviceTypeId: ai.deviceTypeId,
            deviceTypeName: ai.deviceTypeName,
            deviceName: ai.deviceName,
            dataType: ai.dataType,
            devices: [ai]
          });
          map[ai.deviceTypeId] = ai;
        } else {
          for (let j = 0; j < dest.length; j++) {
            const dj = dest[j];
            if (dj.deviceTypeId === ai.deviceTypeId) {
              dj.devices.push(ai);
              break;
            }
          }
        }
      }
    }
    return dest;
  }

  // 获取设备参数并进行分组
  getLiftDeviceParams(data): Observable<any> {
    return new Observable(responseObserver => {
      let deviceIdAndDeviceParam = [];
      const arr = [];
      for (const datas of data) {
        for (const data of datas.deviceParameters) {
          arr.push({ deviceId: datas.deviceId, deviceParameterCode: data.parameterCode });
          deviceIdAndDeviceParam = arr;
        }
      }
      this.dataservice.getDeviceRealParams(deviceIdAndDeviceParam).subscribe(res => {
        for (const datas of data) {
          for (const data of res.data.datas) {
            if (data.deviceId === datas.deviceId) {
              for (const item of datas.deviceParameters) {
                if (data.deviceParameterCode === item.parameterCode) {
                  Object.assign(item, data);
                }
              }
            }
          }
        }
        console.log('未分组', data);
        // 计算顶部各项总数
        this.getTopInfo(data);
        // 获取房间参数
        this.getRoomsParams(data);
        // 数据按照设备类型进行分组
        data = this.getGroup(data);
        console.log(data)
        //   // 如果有摄像头设备类型直接分组，没有则添加新分组
        if (this.deviceVideoList && this.deviceVideoList.length) {
          for (const item of this.deviceVideoList) {
            item.deviceParameters = [];
            item.deviceName = item.cameraName;
          }
          let Num = 0;
          for (const dat of data) {
            if (dat.deviceTypeId === 4600) {
              Num += 1;
              for (const item of this.deviceVideoList) {
                dat.devices.push(item);
              }
            }
          }
          if (!Num) {
            const obj = {
              deviceTypeName: '摄像头',
              devices: this.deviceVideoList,
            }
            data.push(obj);
          }
        }
        console.log('已分组', data);
        responseObserver.next(data);
        responseObserver.complete();
      });
    });
  }

  // 处理数据图标显示逻辑
  dealData(data) {
    // 判断显示图标
    console.log('数据处理', data)
    for (const m of data) {
      for (const k of m.devices) {
        for (let n = k.deviceParameters.length - 1; n >= 0; n--) {
          if (k.deviceParameters[n].value === null || k.deviceParameters[n].deviceValue === null) {
            k.deviceParameters.splice(n, 1)
          }
        }
        const status = this.liftService.observe(k.deviceParameters);
        if (status) {
          if (status.Roomimg) {
            k.isOpen = status.ontxt;
            if (k.alarm && k.alarmLevel) {
              k.roomSrc = 'assets/imgs/gallery/SVG/20035.svg';
            } else {
              k.roomSrc = 'assets/imgs/gallery/SVG/' + status.Roomimg + '.svg';
            }
          }
          if (status.isRun) {
            k.isRun = status.isRun;
          }
        } else {
          k.isRun = true;
        }

      }
    }
    return data;
  }


  // 将告警加入响应的设备及参数
  addAlarmToDevice(data, projectId, deviceSysId): Observable<any> {
    return new Observable(responseObserver => {
      this.dataservice.getLiftAlarm(projectId, deviceSysId).subscribe(res => {
        this.alarmInfos = res.data;
        for (const item of this.alarmInfos) {
          item.deviceValueLastTime = item.deviceValueLastTime.substr(0, item.deviceValueLastTime.length - 4);
        }
        console.log('电梯设备告警', this.alarmInfos);
        if (this.alarmInfos) {
          this.autoScroll(this.alarmInfos.length); // 参数为告警信息数
        }

        // 将告警分给对应的设备
        for (const m of data) {
          for (const k of m.devices) {
            k.alarmLevel = 0;
            const alarmLevel = [];
            let alarmLevelMax;
            if (res.data.length) {
              for (const l of res.data) {
                if (l) {
                  if (k.deviceId === l.deviceId) {
                    alarmLevel.push(l.alarmLevel);
                  } else {
                    alarmLevel.push(0);
                  }
                }
              }
            } else {
              alarmLevel.push(0);
            }
            // 获取告警等级(最大值)
            alarmLevelMax = Math.max.apply(null, alarmLevel);
            if (alarmLevelMax) {
              k.alarmLevel = alarmLevelMax;
            } else {
              k.alarmLevel = 0;
            }
            for (const val of k.deviceParameters) {
              val.alarmLevel = k.alarmLevel;
            }
          }
        }
        responseObserver.next(data);
        responseObserver.complete();
      });
    });
  }


  // 获取房间参数
  getRoomsParams(data) {
    const Params = [];
    if (data) {
      for (const params of data) {
        if (params.dataType === 2) {
          Params.push(params);
        }
      }
    }
    this.Params = Params;
    // 移除设备类型参数通讯状态
    for (let i = 0; i < this.Params.length; i++) {
      for (let j = this.Params[i].deviceParameters.length - 1; j >= 0; j--) {
        if (this.Params[i].deviceParameters[j].parameterCode === 9) {
          this.Params[i].deviceParameters.splice(j, 1);
        } else if (this.Params[i].deviceParameters[j].parameterCode === 1) {
          this.Params[i].deviceParameters[j].splice(j, 1);
        } else if (this.Params[i].deviceParameters[j].parameterCode === 3) {
          this.Params[i].deviceParameters[j].splice(j, 1);
        }
      }
    }
    console.log('房间参数', this.Params);
  }


  // 计算头部四项参数
  getTopInfo(data) {
    let run = 0;
    let stop = 0;
    let fault = 0;
    let service = 0;
    const res = [];

    for (let i = 0; i < data.length; i++) {
      data[i].service = 0;
      data[i].alarm = 0;
      for (let m = 0; m < data[i].deviceParameters.length; m++) {
        if ((data[i].deviceTypeId === 3101 || data[i].deviceTypeId === 3102) && data[i].deviceParameters[m].parameterCode === 9 && data[i].deviceParameters[m].value === 1) {
          res.push(data[i]);
        }
      }
    }

    for (let i = 0; i < res.length; i++) {
      for (let m = 0; m < res[i].deviceParameters.length; m++) {
        if (res[i].deviceParameters[m].parameterCode === 1720 && res[i].deviceParameters[m].value === 1) {
          service += 1;
          res[i].service = 1;
        }
      }
    }

    const alarmArr = [];
    for (let i = 0; i < res.length; i++) {
      if (res[i].service === 0) {
        for (let m = 0; m < res[i].deviceParameters.length; m++) {
          if (res[i].deviceParameters[m].parameterCode === 2 && res[i].deviceParameters[m].value === 1) {
            res[i].alarm = 1;
          }
        }
      }
    }

    for (let i = 0; i < res.length; i++) {
      if (res[i].service === 0) {
        for (let m = 0; m < res[i].deviceParameters.length; m++) {
          if (res[i].deviceParameters[m].parameterCode >= 1710 && res[i].deviceParameters[m].parameterCode <= 1719 && res[i].deviceParameters[m].value === 1) {
            res[i].alarm = 1;
          }
        }
      }
    }

    for (const item of res) {
      if (item.alarm === 1) {
        console.log(item);
        alarmArr.push(item);
      }
    }
    console.log('存在故障的设备', alarmArr)
    fault = alarmArr.length;
    for (let i = 0; i < res.length; i++) {
      if (res[i].service === 0 && res[i].alarm === 0) {
        for (let m = 0; m < res[i].deviceParameters.length; m++) {

          if (res[i].deviceParameters[m].parameterCode === 1) {
            switch (res[i].deviceParameters[m].value) {
              case 0:
                stop += 1;
                break;
              case 1:
                run += 1;
                break;
            }
          }
        }
      }
    }

    this.services = service;
    this.faults = fault;
    this.stops = stop;
    this.runs = run;
  }

  async toDeviceVideo(data) {
    console.log(data)
    const config = {
      title: this.cache.currentProject.projectName + this.sysName + data.cameraName,
      message: [],
      deviceVideoList: [data],
      // areaId: this.roomGroups[this.selectedRoomIndex].areaId,
      deviceId: data.deviceId
    };
    const VideoModal = await this.modalCtrl.create({
      component: DeviceVideoModal,
      componentProps: { config: config }
    });
    await VideoModal.present();
  }

  // 告警滚动
  autoScroll(len) {
    const step = -90;
    let top = 1;
    const ele = this.el.nativeElement.querySelector('.Text-init');
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
      this.renderer.setStyle(ele, 'transition', 'unset');
      this.renderer.setStyle(ele, 'top', 0 + 'px');
    }
    this.autoScrollInterval = setInterval(() => {
      if (top < len) {
        this.renderer.setStyle(ele, 'top', top * step + 'px');
        if (top === 1) {
          this.renderer.setStyle(ele, 'transition', 'top 1s');
        }
        top++;
      } else {
        top = 0;
        this.renderer.setStyle(ele, 'transition', 'unset');
      }
    }, 2000);
  }

  // 跳转设备房间页
  toDevicePage(device, index, group) {
    const data = {
      devices: group.devices,
      index: index,
      device: device
    };
    this.emitService.deviceLift = data;
    this.navCtrl.navigateForward(['tabs/home/LiftPage'], {
      queryParams: data
    });
  }

  getVideoList(areaIds) {
    this.deviceVideoList = [];
    this.videoList = [];
    this.dataservice.getLiftRoomVideoList(areaIds).subscribe(res => {
      const cameraOne = [];
      const cameraTwo = [];
      for (let i = 0; i < res.data.datas.length; i++) {
        if (res.data.datas[i].position === 1) {
          cameraOne.push(res.data.datas[i])
        } else if (res.data.datas[i].position === 2) {
          cameraTwo.push(res.data.datas[i])
        }
      }
      console.log('设备区摄像头', cameraOne)
      this.deviceVideoList = cameraOne;
      this.videoList = cameraTwo;
    });
  }

  // 控制单位显示是否换行
  // 判断文字与单位是否超过显示行
  toResult() {
    if (this.el.nativeElement.querySelectorAll('.text')) {
      const elText = this.el.nativeElement.querySelectorAll('.text');
      for (let i = 0; i < elText.length; i++) {
        if (elText[i].children[0].innerHTML.length >= (Math.ceil(elText[i].children[0].offsetHeight / 16) * 8 - 4)) {
          // 判断单位宽度与文字宽度是否大于总宽度
          if (elText[i].children[2]) {
            if (elText[i].offsetWidth < elText[i].children[0].offsetWidth +
              elText[i].children[1].offsetWidth + elText[i].children[2].offsetWidth) {
              if (elText[i].children[0]) {
                this.renderer.setStyle(elText[i].children[0], 'display', 'block');
              }
            } else {
              if (elText[i].children[1]) {
                this.renderer.setStyle(elText[i].children[1], 'display', 'inline-block');
              }
            }
          } else {
            if (elText[i].children[1]) {
              if (elText[i].offsetWidth < elText[i].children[0].offsetWidth + elText[i].children[1].offsetWidth) {
                if (elText[i].children[0]) {
                  this.renderer.setStyle(elText[i].children[0], 'display', 'block');
                }
              } else {
                if (elText[i].children[1]) {
                  this.renderer.setStyle(elText[i].children[1], 'display', 'inline-block');
                }
              }
            }
          }
        }
      }
    }
  }

  // 文字处理
  WordResult() {
    // 计算内容的高度 来判断是多少行
    const wareNameText = [];
    const heightSome = [];
    const wareName = this.el.nativeElement.querySelectorAll('.device-title');
    for (let i = 0; i < wareName.length; i++) {
      wareNameText[i] = wareName[i].innerHTML;
      heightSome[i] = wareName[i].clientHeight;
      if (heightSome[i] > 30) {
        // 这个42数字是两行的时候的高度，根据你设定的字体大小有关
        for (let k = 0; heightSome[i] > 30; k++) {
          // 每次删掉最后一个然后返回
          wareNameText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1);
          // 重新返回的字符在写在span里面 ，计算新的高度
          wareName[i].innerHTML = wareNameText[i];
          heightSome[i] = wareName[i].clientHeight;
        }
        // 得到正好符合高度的字符，删除最后一个变为省略号 填充在页面里
        const newText = [];
        newText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1) + '...';
        wareName[i].innerHTML = newText[i];
      }
    }
  }

}
